<template>
  <div class="contanier">
    <search-form>
      <template v-slot:formLeft>
        <el-form :inline="true" :model="userFormLine" class="demo-form-inline">
          <el-row>
            <el-col :span="12">
              <div class="grid-content bg-purple">
                <el-form-item>
                  <el-input v-model="userFormLine.name" suffix-icon="el-icon-search" placeholder="请选择或输入专题名称"
                    style="width: 410px"></el-input>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </template>
      <template v-slot:formRight>
        <div class="formRight-btn">
          <el-button icon="el-icon-refresh" @click="onReset" class="overPosBtn">重 置</el-button>
          <el-button type="primary" @click="onSubmit" icon="el-icon-search" class="set-col-btn">查 询</el-button>
        </div>
      </template>
    </search-form>
    <div>
      <search-table>
        <template v-slot:biaoge>
          <template>
            <el-tabs v-model="activeName" @tab-click="handleClick">
              <el-tab-pane label="培训考试中心" name="first" v-if="hasTrainExam">
                <template v-if="courseList.length > 0">
                  <infoBox :title="item.name" class="infoBox" v-for="item in courseList" :key="item.id">
                    <template v-slot:right>
                      <div class="checkAll">
                        <div v-for="(citem, cindex) in item.detail.stageList" :key="cindex" v-if="citem.sortCode == 0" style="display: flex">
                          <div :class="['item', citem.enabledMark == 30 ? '' : 'disabled']"  @click="citem.enabledMark == 30 ? gotoUrl(1, item) : ''">
                            <img src="../../assets/myTrain/jineng.png" class="image" />
                            技能考试
                          </div>
                          <div :class="['item', citem.enabledMark == 30 ? '' : 'disabled']"  @click="citem.enabledMark == 30 ? gotoUrl(2, item) : ''">
                            <img src="../../assets/myTrain/lilun.png" class="image" />
                            理论考试
                          </div>
                        </div>
                        <div class="item" @click="baoMing(item.detail, 2)" v-if="item.detail.enabledMark == 10 || !item.detail.enabledMark">
                          <img src="../../assets/myTrain/baom.png" class="image" />
                          报名
                        </div>
                      </div>
                    </template>
                    <template v-slot:body>
                      <div class="itemall">
                        <el-row :gutter="15" v-if="item.detail">
                          <!-- <el-col :span="6" v-for="(i, idx) in (item.detail.stageList && item.detail.stageList[0] && item.detail.stageList[0].subjectStageRelationList)"> -->
                          <el-col :span="6" v-for="(i, idx) in item.detail.subjectStageRelationListNew" :key="idx">
                            <div class="item">
                              <!-- 已完成、待学习、待自测 -->
                              <!-- enabledMarkOptions: [{"fullName": "未开始", "id": "10"}, {"fullName": "学习中", "id": "20"}, {"fullName": "已完成", "id": "30"}], -->
                              <template v-if="i.enabledMark">
                                <template v-if="i.enabledMark == 10">
                                  <div class="tag self">待自测</div>
                                </template>
                                <template v-else-if="i.enabledMark == 20">
                                  <div class="tag studied">学习中</div>
                                </template>
                                <template v-else-if="i.enabledMark == 30">
                                  <div class="tag completed">已完成</div>
                                </template>
                              </template>
                              <template v-else>
                                <div class="tag self">待自测</div>
                              </template>
                              <!-- <img :src="define.comUrl + item.detail.cover" class="logoImg" /> -->
                              <img :src="define.comUrl + i.cover" class="logoImg" />
                              <div class="content2 optimal-break">
                                {{ i.objectName }}
                              </div>
                              <div class="button" :class="['status-tag', i.process >= 100 ? 'completed' : '']" style="cursor: pointer;"
                                @click="zice(i, item, 1)">{{ i.process >= 100 ? '已完成' : '自测' }}</div>
                            </div>
                          </el-col>
                        </el-row>
                      </div>
                    </template>
                  </infoBox>
                </template>
                <el-empty description="暂无数据" :image-size="120" v-else></el-empty>
              </el-tab-pane>
              <el-tab-pane label="科普中心" name="second">
                <template v-if="courseList2.length > 0">
                  <infoBox :title="item.name" class="infoBox" v-for="item in courseList2" :key="item.id">
                    <template v-slot:right>
                      <div class="checkAll">
                        <div class="item" @click="baoMing(item.detail,1)"
                          v-if="item.detail.enabledMark == 10 || !item.detail.enabledMark">
                          <img src="../../assets/myTrain/baom.png" class="image" />
                          报名
                        </div>
                      </div>
                    </template>
                    <template v-slot:body>
                      <div class="itemall">
                        <el-row :gutter="15" v-if="item.detail">
                          <!-- <el-col :span="6" v-for="(i, idx) in (item.detail.stageList && item.detail.stageList[0] && item.detail.stageList[0].subjectStageRelationList)"> -->
                          <el-col :span="6" v-for="(i, idx) in item.detail.subjectStageRelationListNew" :key="idx">
                            <div class="item">
                              <div class="tag">{{ i.process ? i.process : 0 }}%</div>
                              <!-- <img :src="define.comUrl + item.detail.cover" class="logoImg" /> -->
                              <img :src="define.comUrl + i.cover" class="logoImg" />
                              <div class="content2 optimal-break">
                                {{ i.objectName }}
                              </div>
                              <div class="button" :class="['status-tag', i.process >= 100 ? 'completed' : '']"  style="cursor: pointer;"
                                @click="zice(i, item, 2)">{{ i.process >= 100 ? '已完成' : '未学习' }}</div>
                            </div>
                          </el-col>
                        </el-row>
                      </div>
                    </template>
                  </infoBox>
                </template>
                <el-empty description="暂无数据" :image-size="120" v-else></el-empty>
              </el-tab-pane>
            </el-tabs>
          </template>
        </template>
        <!-- <template v-slot:fenye>
          <div class="set-table-pg-right">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
              :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
          </div>
        </template> -->
      </search-table>
    </div>
    <el-dialog title="注意事项" :visible.sync="showTest" width="545px" :before-close="handleClose">
      <div class="tip">
        <div class="header">
          <div class="text">
            <i class="el-icon-warning-outline" style="margin: 0 0 0 22px"></i>
            亲爱的用户，请认真阅读以下温馨提示：
          </div>
        </div>
        <div class="content">
          <div>科普专题报名后，需学习完其所有视频才可以领取证书哦~</div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showTest = false">关闭</el-button>
        <el-button type="primary" @click="confirmBaoMing(1)" style="background: #2265ee">确定报名</el-button>
      </span>
    </el-dialog>

    <!-- 培训 -->
    <el-dialog title="注意事项" :visible.sync="showTest2" width="545px" :before-close="handleClose">
      <div class="tip">
        <div class="header">
          <div class="text">
            <i class="el-icon-warning-outline" style="margin: 0 0 0 22px"></i>
            亲爱的培训考试用户，请认真阅读以下温馨提示：
          </div>
        </div>
        <div class="content">
          <div>1、专题内每个视频需自测并通过；</div>
          <div>2、自测全通过才可参加专题技能/理论考试；</div>
          <div>3、最终成绩取第一次过及格线的分数。</div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showTest2 = false">关闭</el-button>
        <el-button type="primary" @click="confirmBaoMing(2)" style="background: #2265ee">确定报名</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import infoBox from "@/components/infobox2/index";
import SearchForm from "@/components/search-form";
import SearchTable from "@/components/search-table";
import { checkPermission } from "@/utils/permission";
import { getScopeList, getSubjectDetail, studySubject } from "@/api/exam";
import { getDictionaryDataList } from '@/api/systemData/dictionary'
export default {
  name: "UserManagement",
  components: {
    SearchForm,
    SearchTable,
    infoBox,
  },
  data() {
    return {
      showTest: false,
      showTest2: false,
      courseList: [],
      courseList2: [],
      activeName: "first",
      checkList: [
        {
          logoUrl: "../../assets/myTrain/jineng.png",
          title: "技能考试",
        },
        {
          logoUrl: "../../assets/myTrain/lilun.png",
          title: "理论考试",
        },
        {
          logoUrl: "../../assets/myTrain/baom.png",
          title: "报名",
        },
      ],
      userFormLine: {
        name: "",
      },
      hasTrainExam: true,
      multipleSelection: [],
      currentPage: 1,
      pageSize: 50,
      total: 40,
      currentItem: {},
      certificateOptions: [],
      categoryId: null,
      categoryId2: null,
    };
  },
  created() {
    this.hasTrainExam = checkPermission('TrainExam', '664052738669150213');
    if (!this.hasTrainExam) {
      this.activeName = 'second';
    }
    this.getDicList();
    // this.getList();
  },
  methods: {
    onReset() {
      this.userFormLine = {};
      this.getList();
    },
    onSubmit() {
      this.getList();
    },
    // 考试
    gotoUrl(val, item) {

      //if (item.detail.stageList && item.detail.stageList[0] && item.detail.stageList[0].process >= 100) {
        //  this.$message.warning("请先完成所有自测");
        //  return;
        //}

      if (item.detail && item.detail.stageList && item.detail.stageList.length > 0) {
        const id = item.detail.stageList[val].subjectStageRelationList[0].objectId
        if (val === 1) {
          this.$router.push({
            path: "/zice/index",
            query: {
              id: id,
            },
          });
        } else if (val === 2) {
          this.$router.push({
            path: "/zice/index",
            query: {
              id: id,
            },
          });
        }
      }
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
    },
    // 看视频
    zice(i, item, type, enabledMark) {
      if (item.detail.enabledMark == 10 || !item.detail.enabledMark) {
        this.$message.warning("请先报名");
        return;
      }
      this.$router.push({
        path: "/zicesp/index",
        query: {
          id: i.objectId,
          type: type,
          enabledMark: (i.enabledMark ? i.enabledMark : -1)
        },
      });
    },
    getDicList() {
      getDictionaryDataList('559344237955514629', {
        keyword: '',
        isTree: 0
      }).then(res => {
        this.certificateOptions = res.data.list;
        for(let i in this.certificateOptions) {
          if (this.certificateOptions[i].enCode == 'Leader') {
            this.categoryId = this.certificateOptions[i].id;
          }
          if (this.certificateOptions[i].enCode == 'Common') {
            this.categoryId2 = this.certificateOptions[i].id;
          }
        }
        this.getList();
      })
    },
    getList() {
      // 培训考试中心
      getScopeList({
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        ...this.userFormLine,
        categoryId: this.categoryId,
        enabledMark: 1,
      }).then((res) => {
        if (res.code === 200 && res.data.list.length > 0) {
          const detailPromises = res.data.list.map(item => {
            return getSubjectDetail(item.id).then(detailRes => {
              if (detailRes.code === 200) {
                item.detail = detailRes.data;
              }
              return item;
            });
          });

          // isProcess 自测是否全部完成
          Promise.all(detailPromises).then(completedItems => {
            completedItems.forEach(item => {

              item.detail.subjectStageRelationListNew = [];
              let stageList = item.detail.stageList;
              if (stageList) {
                stageList.forEach(fItem => {
                  if(fItem.sortCode == 0) {
                    let subjectStageRelationList = fItem.subjectStageRelationList;
                    subjectStageRelationList.forEach(sItem => {
                      item.detail.subjectStageRelationListNew.push(sItem);
                    });
                  }
                });
              }
              
              // 貌似没有用到
              item.isProcess = (
                  item.stageList && 
                  item.stageList.length > 0 &&
                  item.stageList.every(cItem => 
                      cItem.subjectStageRelationList &&
                      cItem.subjectStageRelationList.length > 0 &&
                      cItem.subjectStageRelationList.every(pItem => 
                          pItem.process >= 100
                      )
                  )
              ) || false; // 如果前面是 undefined/null，默认 false

            });

            this.courseList = completedItems;
          });
        } else {
          this.courseList = [];
        }
      });

      // 科普
      getScopeList({
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        ...this.userFormLine,
        categoryId: this.categoryId2
      }).then((res) => {
        if (res.code === 200 && res.data.list.length > 0) {
          const detailPromises = res.data.list.map(item => {
            return getSubjectDetail(item.id).then(detailRes => {
              if (detailRes.code === 200) {
                item.detail = detailRes.data;
              }
              return item;
            });
          });

          Promise.all(detailPromises).then(completedItems => {
            completedItems.forEach(item => {
              item.detail.subjectStageRelationListNew = [];
              let stageList = item.detail.stageList;
              if (stageList) {
                stageList.forEach(fItem => {
                  let subjectStageRelationList = fItem.subjectStageRelationList;
                  subjectStageRelationList.forEach(sItem => {
                    item.detail.subjectStageRelationListNew.push(sItem);
                  });
                });
              }
            });
            this.courseList2 = completedItems;
          });

        } else {
          this.courseList2 = [];
        }
      });
    },
    baoMing(item, type) {
      this.currentItem = item;
      if (type == 1) {
        this.showTest = true;
      }
      else if (type == 2){
        this.showTest2 = true;
      }
    },
    confirmBaoMing(type) {
      studySubject(this.currentItem.id).then(res => {
        if (res.code === 200) {
          this.$message.success("报名成功");
          if (type == 1) {
            this.showTest = false;
          }
          else if (type == 2){
            this.showTest2 = false;
          }
          this.getList();
        }
      });
    },
    handleClose() {

    },
  },
};
</script>
<style scoped lang="scss">
.self {
  color: #41CA37;
}
.completed {
  color: #323232;
}
.studied {
  color: #EEB930;
}
.nosure {
  width: 143px;
  height: 50px;
  border-radius: 6px;
  border: 1px solid #e2e7f5;
  font-size: 19px;
  color: #101010;
  line-height: 19px;
  text-align: right;
  display: flex;
  justify-content: center;
  align-items: center;
  font-style: normal;
}

.sure {
  width: 143px;
  height: 50px;
  background: #2265ee;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 6px;
  font-weight: 400;
  font-size: 19px;
  color: #ffffff;
  line-height: 19px;
  text-align: right;
  font-style: normal;
}

.tip {
  width: 100%;
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;

  .header {
    width: 95%;
    height: 46px;
    background: #fffbe8;
    border-radius: 4px;
    display: flex;

    align-items: center;

    .text {
      font-size: 14px;
      color: #ed6a0c;
      line-height: 26px;
      text-align: left;
      font-style: normal;
    }
  }

  .content {
    width: 88%;
    margin-top: 16px;

    background: #ffffff;

    font-size: 16px;
    color: #323232;
    line-height: 33px;
    text-align: left;
    font-style: normal;
    display: flex;
    flex-direction: column;
  }
}

.checkAll {
  display: flex;
  flex-direction: row;

  .item {
    width: 143px;
    height: 36px;
    display: flex;
    justify-content: center;
    align-items: center;

    font-size: 13px;
    color: #2265ee;
    line-height: 18px;
    text-align: right;
    font-style: normal;
    text-decoration-line: underline;
    cursor: pointer;

    .image {
      width: 20px;
      height: 20px;
    }
  }

  .item.disabled {
    color: #999;
  }

  .item.disabled img {
    filter: grayscale(100%);
  }

  .item-no {
    width: 143px;
    height: 36px;
    display: flex;
    justify-content: center;
    align-items: center;

    font-size: 13px;
    color: #a4afca;
    line-height: 18px;
    text-align: right;
    font-style: normal;
    text-decoration-line: underline;

    .image {
      width: 20px;
      height: 20px;
    }
  }
}

.itemall {
  width: 100%;

  /* 添加此行以允许换行 */

  .item {
    width: 100%;
    margin-top: 17px;

    display: flex;
    position: relative;

    align-items: center;
    flex-direction: column;

    .tag {
      width: 52px;
      height: 24px;
      background: #323232;
      border-radius: 4px;
      position: absolute;

      display: flex;
      margin-top: 12px;
      right: 12px;
      justify-content: center;
      align-items: center;

      font-size: 12px;
      font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI",
        Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue",
        sans-serif;
      color: #ffffff;
      line-height: 22px;
      text-align: right;
      font-style: normal;
    }

    .logoImg {
      width: 100%;
      height: 230px;
      object-fit: cover;
      border-radius: 3px;
      // height: auto;
    }

    .content2 {
      width: 100%;

      font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI",
        Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue",
        sans-serif;

      font-size: 16px;
      color: #323232;
      line-height: 33px;
      font-style: normal;
    }

    .button {
      margin-top: 8px;
      width: 100%;
      height: 36px;
      border-radius: 6px;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 4px;
      border: 1px solid #2265ee;
      font-size: 13px;
      color: #2265ee;
      line-height: 20px;
      text-align: right;
      font-style: normal;
    }
  }
}

/* 鼠标选中时样式 */
::v-deep .el-tabs__item.is-active {
  color: #323232;
  opacity: 1;
}

::v-deep .el-tabs__active-bar {
  background-color: #2265ee;
}

::v-deep .el-tabs__item {
  font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
    Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;

  font-size: 16px;
  color: #323232;
  line-height: 24px;
  text-align: left;
  font-style: normal;
}

::v-deep .el-icon-my-message {
  background: url("../../assets/images/dc.png") no-repeat;
  width: 20px;
  height: 20px;
}

::v-deep .el-icon-my-message:before {
  content: "替";
  font-size: 20px;
  visibility: hidden;
}

::v-deep .el-icon-my-message {
  font-size: 18px;
}

::v-deep .el-icon-my-message:before {
  content: "\e611";
}

.status-tag {
  width: 100%;
  height: 36px;
  margin-top: 8px;
  border-radius: 4px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 13px;
  line-height: 20px;
  text-align: center;
  font-style: normal;

  &.studying {
    background: #FFF3E8;
    color: #ED6A0C;
    border: 1px solid #ED6A0C;
  }

  &.completed {
    background: #EDF8F1;
    color: #52C41A;
    border: 1px solid #52C41A;
  }
}

.optimal-break {
  white-space:nowrap; 
  overflow:hidden; 
  text-overflow:ellipsis;
}
</style>
